<template>
  <view class="content">
    <!-- 验证手机号 -->
    <view>
      <!-- 输入框 -->
      <view class="content">
        <uni-forms
          :rules="rules"
          labelWidth="200"
          ref="form"
          :modelValue="form"
          label-position="top"
        >
          <uni-forms-item
            name="ID_Name"
            label-width="200"
            label="用户名"
            required
          >
            <uni-easyinput
              v-model.trim="form.ID_Name"
              placeholder="请输入用户名"
            />
          </uni-forms-item>

          <uni-forms-item
            name="User_Number"
            label-width="200"
            label="手机号"
            required
          >
            <view class="align-center">
              <uni-easyinput
                v-model.trim="form.User_Number"
                @change="checkPhone"
                placeholder="请输入手机号"
              />
              <view class="mt-2">
                <text v-if="isPhone" class="text-danger ml-2"
                  >该手机号已被注册</text
                >
              </view>
            </view>
          </uni-forms-item>

          <uni-forms-item label-width="200" label="用户身份">
            <uni-data-select
              v-model="form.User_Type"
              :localdata="identitys"
              @change="change"
            ></uni-data-select>
          </uni-forms-item>

          <uni-forms-item
            name="Pass_Ward"
            label-width="200"
            label="设置密码"
            required
          >
            <uni-easyinput
              type="password"
              v-model.trim="form.Pass_Ward"
              placeholder="请输入密码"
            />
          </uni-forms-item>

          <uni-forms-item
            label-width="200"
            label="确认密码"
            required
            name="ConfirmPassword"
          >
            <uni-easyinput
              type="password"
              v-model.trim="form.ConfirmPassword"
              placeholder="请再次输入密码"
              @change="password_authentication"
            />
          </uni-forms-item>

          <uni-forms-item
            label-width="200"
            label="短信验证码"
            required
            name="code"
          >
            <view class="code">
              <uni-easyinput
                v-model.trim="form.code"
                placeholder="请输入短信验证码"
              />
              <button
                @click="sendMessage"
                v-if="time"
                size="mini"
                class="flex align-center"
                style="height: 37px"
              >
                获取验证码
              </button>
              <button
                @click="sendMessage"
                v-else
                class="flex align-center"
                style="height: 37px"
              >
                {{ secend }}
              </button>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
      <!-- 用户协议 -->
      <view class="flex justify-center align-center my-5 font">
        <checkbox-group>
          <label class="flex align-center">
            <checkbox @click="updateCheckValue" :disabled="!loading" />
            <view
              >注册即代表您同意<text
                class="text-success"
                @click="
                  goRegistered('/pages/My/Aboutus/User_Service_Agreement')
                "
                >《用户服务协议》</text
              ></view
            >
          </label>
        </checkbox-group>
      </view>
      <!-- 下一步按钮 -->
      <view class="flex justify-center align-center flex-column">
        <button size="mini" @click="saveForm()" :disabled="!isAgree">
          注册
        </button>
        <view class="foot" @click="Login">
          <text class="mr-1">已有账号</text>
          <text>去登陆></text>
        </view>
      </view>
    </view>
    <uni-popup ref="message" type="message">
      <uni-popup-message
        :type="msgType"
        :message="messageText"
        :duration="2000"
      ></uni-popup-message>
    </uni-popup>
  </view>
</template>

<script>
const app = getApp();
import { register, checkPhone } from "../../api/login.js";
import {
  getInquiryIDOriginal,
  getEditAction,
  RedisAdd,
  isPhoneCode,
} from "@/api/global.js";
export default {
  name: "Registered",
  data() {
    return {
      loading: false,
      isPhone: false,
      isAgree: false,
      screenWidth: uni.getSystemInfoSync().windowWidth,
      ThemeColors: app.globalData.ThemeColors,
      activeName: "first",
      timer: null,
      time: true,
      secend: 60,
      RandomCode: "",
      form: {
        User_Number: "",
        Pass_Ward: "",
        ID_Name: "",
        User_Type: "",
        Authentication: "",
        ConfirmPassword: "",
        code: "",
      },
      identitys: [
        {
          value: 0,
          text: "商协会",
        },
        {
          value: 1,
          text: "我是买家",
        },
        {
          value: 2,
          text: "我是卖家",
        },
      ],
      rules: {
        ID_Name: {
          rules: [
            {
              required: true,
              errorMessage: "请输入用户名",
              trigger: "blur",
            },
          ],
        },
        User_Number: {
          rules: [
            {
              required: true,
              errorMessage: "请输入手机号",
              trigger: "blur",
            },
            // {
            //   pattern: /^1[3456789]\d{9}$/,
            //   errorMessage: '手机号码格式不正确',
            //   trigger: 'blur'
            // }
          ],
        },
        Pass_Ward: {
          rules: [
            {
              required: true,
              errorMessage: "请输入密码",
              trigger: "blur",
            },
          ],
        },
        ConfirmPassword: {
          rules: [
            {
              required: true,
              errorMessage: "请输入确认密码",
              trigger: "blur",
            },
          ],
        },
        code: {
          rules: [
            {
              required: true,
              errorMessage: "请输入验证码",
              trigger: "blur",
            },
          ],
        },
      },
      msgType: "success",
      messageText: "这是一条成功提示",
      checkvalue: 0,
    };
  },
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules);
  },
  methods: {
    password_authentication() {
      if (this.form.ConfirmPassword !== this.form.Pass_Ward) {
        this.messageToggle("error", "两次密码输入不一致");
        this.loading = false;
      } else if (this.form.ConfirmPassword.length >= 6) {
        this.messageToggle("error", "密码长度不够");
      } else {
        this.loading = true;
      }
    },
    updateCheckValue() {
      if (this.checkvalue == 0) {
        this.checkvalue = 1;
        this.isAgree = !this.isAgree;
      } else {
        this.checkvalue = 0;
        this.isAgree = !this.isAgree;
      }
    },
    // 验证手机号
    async checkPhone() {
      if (this.form.User_Number == "") {
        this.isPhone = false;
      }
      const res = await checkPhone({
        data: {
          User_Number: this.form.User_Number,
        },
      });
      console.log(res);
      if (res.Status == "success" && this.form.User_Number !== "") {
        this.isPhone = false;
      } else if (res.Status == "fail" && this.form.User_Number !== "") {
        this.isPhone = true;
      }
    },
    // validateConfirmPassword
    //注册
    async register() {
      const res = await register({
        data: {
          Data: JSON.stringify({
            system_user_info: [this.form],
          }),
        },
      });
      if (res.Status !== "success") return Message.error("注册失败");
      this.messageToggle("success", "注册成功");
      uni.navigateTo({
        url: "/pages/My/Login",
      });
    },
    //验证短信验证码
    async CheckCode(data) {
      const res = await isPhoneCode({
        data,
      });
      if (res.Status == "success") {
        //解除禁用注册键
        this.register();
      } else {
        this.messageToggle("error", "短信验证码错误");
      }
    },
    //验证表单
    saveForm() {
      this.$refs.form
        .validate()
        .then((res) => {
          console.log(res);
          let Data = {
            Code: this.form.code,
            Phone: this.form.User_Number,
          };
          console.log(Data);
          this.CheckCode(Data);
        })
        .catch((err) => {
          console.log(err);
          this.messageToggle("error", "请检查页面表单是否填写正确");
        });
      // this.$refs.form.validate((valid) => {
      //   console.log(valid);
      //   if (valid) {
      //     let Data = {
      //       Code: this.form.code,
      //       Phone: this.form.User_Number
      //     }
      //     console.log(Data);
      //     this.CheckCode(Data)
      //   } else {
      //     console.log('请检查页面表单是否填写正确');
      //     // Message({
      //     //   type: 'error',
      //     //   message: ''
      //     // })
      //   }
      // });
    },
    Login() {
      uni.navigateTo({
        url: "/pages/My/Login",
      });
    },
    //用户服务协议
    goRegistered() {
      uni.navigateTo({
        url,
      });
    },
    //提示
    change() {
      if (uni.getStorageSync("userType") != "1") {
        this.messageToggle("info", "选定身份注册后不会影响您的其他交易行为");
        uni.setStorageSync("userType", "1");
      }
    },
    messageToggle(type, text) {
      this.msgType = type;
      this.messageText = text;
      this.$refs.message.open();
    },
    //验证手机号
    sendMessage() {
      if (this.form.User_Number == "") {
        this.messageToggle("error", "请先输入正确的手机号再点击发送");
        return;
      }
      const reg = /^1[3-9]\d{9}$/;
      if (!reg.test(this.form.User_Number)) {
        this.messageToggle("error", "请检查手机号格式是否正确!");
        return;
      }
      if (this.isPhone) {
        this.messageToggle("error", "您输入的手机号已被注册!");
        return;
      }
      this.time = false;
      this.secend = 60;
      this.secend--;
      this.timer = setInterval(() => {
        if (this.secend == "01") {
          clearInterval(this.timer);
          this.time = true;
          return;
        }
        this.secend--;
        if (this.secend < 10) {
          this.secend = "0" + this.secend;
        }
      }, 1000);
      let code = "";
      for (let i = 0; i < 6; i++) {
        code += parseInt(Math.random() * 10);
      }
      this.RandomCode = code;
      uniCloud
        .callFunction({
          name: "sendSms", //对应的云函数名
          data: {
            phone: this.form.User_Number,
            data: {
              name: "众菌联",
              code: this.RandomCode, //随机生成的验证码，如123456
              action: "注册", //校验类型为“注册”
              expMinute: "5", //短信的有效期，5分钟
            },
          },
        })
        .then((res) => {
          if (res.success) {
            this.messageToggle("success", "短信已发送!");
            this.RedisPush();
          }
        })
        .catch((msg) => {
          console.log(msg);
          this.messageToggle("error", "系统错误!请稍后重试");
        });
    },
    async RedisPush() {
      const res = await RedisAdd({
        data: {
          Key: "zjl_" + this.form.User_Number,
          Main: JSON.stringify({
            code: this.RandomCode,
            expires_in: parseInt(new Date().getTime() / 1000) + 300,
          }),
          Expire: 300,
        },
      });
      console.log(res);
    },
  },
};
</script>

<style lang="scss">
.content {
  background-color: #fff;
  padding: 20rpx;
  box-sizing: border-box;

  .code {
    display: flex;
    align-items: center;

    uni-button {
      height: 72rpx;
      line-height: 72rpx;
      font-size: 24rpx;
    }
  }

  .foot {
    margin: 20rpx 0;
  }
}
</style>
